<?php

namespace App\Store\Controllers\Order;

use App\Store\Services\Message\WxaccountMessage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Member\MemberBalanceChangelog;
use App\Store\Models\Order\OrderRecharge;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Member\Member;


use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\Account;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Member\MemberPointsChangelog;
use App\Store\Models\Member\SiteMemberLv;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;
use App\Store\Services\Financial;
use App\Store\Services\Member\CommonMember;
use App\Store\Services\Order\OrderRecharge as ServicesOrderOrderRecharge;
use App\Store\Services\Order\OrderSales;
use Illuminate\Support\Facades\DB;

use App\Store\Validate\Order\OrderRecharge as ValidateOrderOrderRecharge;
use Illuminate\Support\Facades\Log;

/**
 * 充值开单
 */
class OrderRechargeController extends Controller
{
    /**
     * 开单
     */
    public function dopostorder(Request $request)
    {

        $req_data = $request->only([
            'mobile', 'real_name','mem_card_no','lunar_bdate','solar_bdate','points_current','money','send_money','send_points', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'pay_type_id', 'order_at', 'issendpoints','remark','mixed_payment'
        ]);
        $Validate = new ValidateOrderOrderRecharge();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }


        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $orderdata=[
            'money'=>$req_data['money'],
            'send_money'=>$req_data['send_money'],
            'send_points'=>intval($req_data['send_points']) ?? 0,
            'shopping_account_id1'=>$req_data['shopping_account_id1'],
            'shopping_account_id2'=>isset($req_data['shopping_account_id2'])?intval($req_data['shopping_account_id2']):0,
            'classesset_id'=>isset($req_data['classesset_id'])?intval($req_data['classesset_id']):0,
            'pay_type_id'=>isset($req_data['pay_type_id'])?intval($req_data['pay_type_id']):0,
            'mixed_payment' => (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']) ,
            'order_at' => isset($req_data['order_at']) ?strtotime($req_data['order_at']):time(),
            'issendpoints' => isset($req_data['issendpoints']) ? intval($req_data['issendpoints']) : 1,
            'remark'=>isset($req_data['remark'])?$req_data['remark']:''
        ];
        // $orderdata['order_at']=strtotime($orderdata['order_at']);
        $meminfo=Member::query()->where(['cp_id'=>$cp_id,'mobile'=>$req_data['mobile'],'is_del'=>1])->first();
        $current_store_id=0;
        $store_ids = $accountinfo['store_ids'];
        if (is_array($store_ids) || $store_ids == '' || $store_ids<=0) { //获取当前权限下的门店

            return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
        }else{
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }
        if(!$meminfo){
            $memdata=[
                'cp_id'=>$cp_id,
                'store_id'=>$current_store_id,
                'mobile'=>$req_data['mobile'],
                'real_name'=>isset($req_data['real_name'])?$req_data['real_name']:'',
                'mem_card_no'=>isset($req_data['mem_card_no'])?$req_data['mem_card_no']:'',
                'lunar_bdate'=>isset($req_data['lunar_bdate'])?$req_data['lunar_bdate']:'',
                'solar_bdate'=>isset($req_data['solar_bdate'])?$req_data['solar_bdate']:'',
                'points_current'=>isset($req_data['points_current'])?intval($req_data['points_current']):0,
                'points_total'=>isset($req_data['points_current'])?intval($req_data['points_current']):0,
                'create_at'=>time(),
                'update_at'=>time(),
                'create_account_id' => $accountinfo['id'],
                'update_account_id' => $accountinfo['id'],
                'create_account_real_name' => $accountinfo['real_name'],
                'update_account_real_name' => $accountinfo['real_name'],
            ];

            $ins_mem_id=Member::create($memdata)->id;

            CommonMember::setMemInitPoints($request,$ins_mem_id);
        }
        $orderdata['mem_id']=$meminfo->id;

        $orderdata['cp_id']=$cp_id;
        $orderdata['store_id']=$current_store_id;
        $orderdata['order_sn']=StoreCommon::createOrderSn();
        $orderdata['pay_type_name']=$req_data['pay_type_id'] == -1 ?'混合支付':PaytypeList::where(['id'=>$req_data['pay_type_id']])->value('paytype_name');

        $orderdata['create_account_id'] = $accountinfo['id'];
        $orderdata['update_account_id'] = $accountinfo['id'];
        $orderdata['create_account_real_name'] = $accountinfo['real_name'];
        $orderdata['update_account_real_name'] = $accountinfo['real_name'];
        $orderdata['create_at'] = time();
        $orderdata['update_at'] = time();
        $orderid=OrderRecharge::create($orderdata)->id;



        $printdata=$request->is_print==1 ? ServicesOrderOrderRecharge::getOrderPrintData($orderid):[];

        $info = OrderRecharge::where(['id' => $orderid, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if(!empty($info)){
            //计算绩效？
            //订单成功发送短信
            $info->change_before = $meminfo->pre_money;
            $info->change_after = $meminfo->pre_money + $info->money + $info->send_money;
            WxaccountMessage::sendwx($cp_id, $info->mem_id, 'recharge_order', $info->toArray());
            WxaccountMessage::sendwxinner($cp_id, $info->store_id, 'recharge_order', $info->toArray());
        }



        return response()->json(['code' => '000', 'msg' => '开单成功','data'=>$printdata]);

    }

    /**
     * 开单
     */
    public function dopostordermaker(Request $request)
    {

        $req_data = $request->only([
            'mobile', 'real_name','mem_card_no','lunar_bdate','solar_bdate','points_current','money','send_money','send_points', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'pay_type_id', 'order_at', 'issendpoints','remark','mixed_payment'
        ]);
        $Validate = new ValidateOrderOrderRecharge();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $orderdata=[
            'money'=>$req_data['money'],
            'send_money'=>$req_data['send_money'],
            'send_points'=>$req_data['send_points'],
            'shopping_account_id1'=>$req_data['shopping_account_id1'],
            'shopping_account_id2'=>$req_data['shopping_account_id2'],
            'classesset_id'=>$req_data['classesset_id'],
            'pay_type_id'=>$req_data['pay_type_id'],
            'mixed_payment' => (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']) ,
            'order_at' => isset($req_data['order_at']) ?strtotime($req_data['order_at']):time(),
            'issendpoints'=>$req_data['issendpoints'],
            'remark'=>isset($req_data['remark'])?$req_data['remark']:''
        ];
        // $orderdata['order_at']=strtotime($orderdata['order_at']);
        $meminfo=Member::where(['cp_id'=>$cp_id,'mobile'=>$req_data['mobile'],'is_del'=>1])->first();
        $current_store_id=0;
        $store_ids = $accountinfo['store_ids'];
        if (is_array($store_ids) || $store_ids == '' || $store_ids<=0) { //获取当前权限下的门店

            return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
        }else{
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }
        if(!$meminfo){
            $memdata=[
                'cp_id'=>$cp_id,
                'store_id'=>$current_store_id,
                'mobile'=>$req_data['mobile'],
                'real_name'=>isset($req_data['real_name'])?$req_data['real_name']:'',
                'mem_card_no'=>isset($req_data['mem_card_no'])?$req_data['mem_card_no']:'',
                'lunar_bdate'=>isset($req_data['lunar_bdate'])?$req_data['lunar_bdate']:'',
                'solar_bdate'=>isset($req_data['solar_bdate'])?$req_data['solar_bdate']:'',
                'points_current'=>isset($req_data['points_current'])?intval($req_data['points_current']):0,
                'create_at'=>time(),
                'update_at'=>time(),
                'create_account_id' => $accountinfo['id'],
                'update_account_id' => $accountinfo['id'],
                'create_account_real_name' => $accountinfo['real_name'],
                'update_account_real_name' => $accountinfo['real_name'],
            ];
            Member::create($memdata);
        }
        $meminfo=Member::where(['cp_id'=>$cp_id,'mobile'=>$req_data['mobile']])->first();
        $orderdata['mem_id']=$meminfo->id;

        $orderdata['cp_id']=$cp_id;
        $orderdata['store_id']=$current_store_id;
        $orderdata['order_sn']=date('YmdHis') .$cp_id.$current_store_id. rand(1000, 9999);
        $orderdata['pay_type_name']=$req_data['pay_type_id'] == -1 ?'混合支付':PaytypeList::where(['id'=>$req_data['pay_type_id']])->value('paytype_name');

        $orderdata['create_account_id'] = $accountinfo['id'];
        $orderdata['update_account_id'] = $accountinfo['id'];
        $orderdata['create_account_real_name'] = $accountinfo['real_name'];
        $orderdata['update_account_real_name'] = $accountinfo['real_name'];
        $orderdata['create_at'] = time();
        $orderdata['update_at'] = time();
        // $orderdata['is_maker']=2;
        OrderRecharge::create($orderdata);

        return response()->json(['code' => '000', 'msg' => '挂单成功']);

    }
    /**
     * 挂单支付
     */
    public function doordermakerpay(Request $request){
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderRecharge::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }
        // if($info->is_maker!=2){
        //     return response()->json(['code' => '001', 'msg' => '该订单不是挂单状态']);
        // }
        OrderRecharge::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['is_maker'=>1,'update_at'=>time()]);
        return response()->json(['code' => '000', 'msg' => '订单支付成功']);

    }
    /**
     * 订单列表
     */

    public function getorderlist(Request $request){
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
            $request->training_min = $training['training_min'];
            $request->training_max = $training['training_max'];
        }
        $list = OrderRecharge::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 订单详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderRecharge::with(['memberinfo','shoppingaccountinfo1','shoppingaccountinfo2','storeinfo'])->where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 订单编辑
     */
    public function doorderedit(Request $request){
        $req_data = $request->only([
            'id','money','send_money','send_points', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'pay_type_id', 'order_at', 'issendpoints','remark','mixed_payment'
        ]);
        $id = $request->id ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = OrderRecharge::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        // if($info->is_maker!=1){
        //     return response()->json(['code' => '001', 'msg' => '该订单挂单中不可编辑']);
        // }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }
        $Validate = new ValidateOrderOrderRecharge('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $orderdata=[
            'money'=>$req_data['money'],
            'send_money'=>$req_data['send_money'],
            'send_points'=>$req_data['send_points'],
            'shopping_account_id1'=>$req_data['shopping_account_id1'],
            'shopping_account_id2'=>$req_data['shopping_account_id2'],
            'classesset_id'=>$req_data['classesset_id'],
            'pay_type_id'=>$req_data['pay_type_id'],
            'mixed_payment' => (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']) ,
            'order_at'=>$req_data['order_at'],
            'issendpoints'=>$req_data['issendpoints'],
            'remark'=>isset($req_data['remark'])?$req_data['remark']:''
        ];
        $orderdata['order_at']=strtotime($orderdata['order_at']);
        $orderdata['pay_type_name']=$req_data['pay_type_id'] == -1 ?'混合支付':PaytypeList::where(['id'=>$req_data['pay_type_id']])->value('paytype_name');

        $orderdata['update_account_id'] = $accountinfo['id'];
        $orderdata['update_account_real_name'] = $accountinfo['real_name'];
        $orderdata['update_at'] = time();
        OrderRecharge::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update($orderdata);

        return response()->json(['code' => '000', 'msg' => '订单编辑成功']);
    }

    /**
     * 审核通过
     */
    public function doorderauditsuccess(Request $request){
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderRecharge::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }
        // if($info->is_maker!=1){
        //     return response()->json(['code' => '001', 'msg' => '该订单挂单中不可审核']);
        // }
        //用户增加余额

        $meminfo=Member::where(['cp_id'=>$cp_id,'id'=>$info->mem_id])->first();
        // print_r($meminfo->pre_money);exit;
        $inslogdata=[];


        $inslogdata[]=[
            'cp_id'=>$cp_id,
            'mem_id'=>$info->mem_id,
            'type'=>1,
            'store_id'=>$info->store_id,
            'change_val'=>$info->money,
            'change_before'=>$meminfo->pre_money,
            'change_after'=>$meminfo->pre_money+$info->money,
            'sales_account_id'=>$info->shopping_account_id1,
            'loginfo'=>json_encode(['title'=>'充值开单']),
            'create_account_id' => $info->create_account_id,
            'update_account_id' => $info->update_account_id,
            'create_account_real_name' => $info->create_account_real_name,
            'update_account_real_name' => $info->update_account_real_name,
            'create_at' => time(),
            'update_at' => time(),
            'remark'=>$info->remark,
        ];
        if($info->send_money>0){
            $inslogdata[]=[
                'cp_id'=>$cp_id,
                'mem_id'=>$info->mem_id,
                'type'=>4,
                'store_id'=>$info->store_id,
                'change_val'=>$info->send_money,
                'change_before'=>$meminfo->pre_money+$info->money,
                'change_after'=>$meminfo->pre_money+$info->money+$info->send_money,
                'sales_account_id'=>$info->shopping_account_id1,
                'loginfo'=>json_encode(['title'=>'充值赠送']),
                'create_account_id' => $info->create_account_id,
                'update_account_id' => $info->update_account_id,
                'create_account_real_name' => $info->create_account_real_name,
                'update_account_real_name' => $info->update_account_real_name,
                'create_at' => time(),
                'update_at' => time(),
                'remark'=>$info->remark,
            ];
        }

        DB::beginTransaction();
        try {

            OrderRecharge::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status'=>2,'audit_at'=>time()]);
            MemberBalanceChangelog::insert($inslogdata);
            Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
            'pre_money'=> DB::raw('pre_money + ' . ($info->money+$info->send_money)),
            ]);


            if($info->send_points>0){
                $pointslogdata=[
                    'cp_id'=>$cp_id,
                    'mem_id'=>$info->mem_id,
                    'type'=>2,
                    'store_id'=>$info->store_id,
                    'change_val'=>$info->send_points,
                    'change_before'=>$meminfo->points_current,
                    'change_after'=>$meminfo->points_current+$info->send_points,
                    'sales_account_id'=>$info->shopping_account_id1,
                    'loginfo'=>json_encode(['title'=>'充值赠送']),
                    'create_account_id' => $info->create_account_id,
                    'update_account_id' => $info->update_account_id,
                    'create_account_real_name' => $info->create_account_real_name,
                    'update_account_real_name' => $info->update_account_real_name,
                    'create_at' => time(),
                    'update_at' => time(),
                    'remark'=>$info->remark,
                ];
                MemberPointsChangelog::create($pointslogdata);

                Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                    'points_current'=> DB::raw('points_current + ' . $info->send_points),
                    'points_total'=> DB::raw('points_total + ' . $info->send_points),
                    ]);

            }

            $info->mem_id>0 && Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                'shopping_times'=>DB::raw('shopping_times + 1 '),
                'shopping_money_total'=>DB::raw('shopping_money_total + '.$info->money),
                'avg_shopping_money'=>intval(($meminfo->shopping_money_total+$info->money)/($meminfo->shopping_times+1)),
                'max_shopping_money'=>($info->money>$meminfo->max_shopping_money?$info->money:$meminfo->max_shopping_money),
                'min_shopping_money'=>($info->money<$meminfo->min_shopping_money?$info->money:$meminfo->min_shopping_money),
                'last_shopping_at'=>$info->create_at
            ]);

            //计算绩效？
            //订单成功发送短信
            $info->change_before = $meminfo->pre_money;
            $info->change_after = $meminfo->pre_money + $info->money + $info->send_money;
            //收支流水
            Financial::createMoneyLog($cp_id,$info,$info->money,-1);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '订单审核成功']);
    }


    public function doorderauditsuccessmore(Request $request){
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);



        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];



        $info_more_arr = OrderRecharge::where(['cp_id' => $cp_id, 'audit_status'=>1])->whereIn('id', $ids)->get();

        if (count($info_more_arr) != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '存在已审核订单']);
        }

        DB::beginTransaction();
        try {
            foreach ($info_more_arr as $info) {
                $id=$info->id;
                $meminfo=Member::where(['cp_id'=>$cp_id,'id'=>$info->mem_id])->first();
                // print_r($meminfo->pre_money);exit;
                $inslogdata=[];


                $inslogdata[]=[
                    'cp_id'=>$cp_id,
                    'mem_id'=>$info->mem_id,
                    'type'=>1,
                    'store_id'=>$info->store_id,
                    'change_val'=>$info->money,
                    'change_before'=>$meminfo->pre_money,
                    'change_after'=>$meminfo->pre_money+$info->money,
                    'sales_account_id'=>$info->shopping_account_id1,
                    'loginfo'=>json_encode(['title'=>'充值开单']),
                    'create_account_id' => $info->create_account_id,
                    'update_account_id' => $info->update_account_id,
                    'create_account_real_name' => $info->create_account_real_name,
                    'update_account_real_name' => $info->update_account_real_name,
                    'create_at' => time(),
                    'update_at' => time(),
                    'remark'=>$info->remark,
                ];
                if($info->send_money>0){
                    $inslogdata[]=[
                        'cp_id'=>$cp_id,
                        'mem_id'=>$info->mem_id,
                        'type'=>4,
                        'store_id'=>$info->store_id,
                        'change_val'=>$info->send_money,
                        'change_before'=>$meminfo->pre_money+$info->money,
                        'change_after'=>$meminfo->pre_money+$info->money+$info->send_money,
                        'sales_account_id'=>$info->shopping_account_id1,
                        'loginfo'=>json_encode(['title'=>'充值赠送']),
                        'create_account_id' => $info->create_account_id,
                        'update_account_id' => $info->update_account_id,
                        'create_account_real_name' => $info->create_account_real_name,
                        'update_account_real_name' => $info->update_account_real_name,
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark'=>$info->remark,
                    ];
                }


                OrderRecharge::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status'=>2,'audit_at'=>time()]);
                MemberBalanceChangelog::insert($inslogdata);
                Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                'pre_money'=> DB::raw('pre_money + ' . ($info->money+$info->send_money)),
                ]);


                if($info->send_points>0){
                    $pointslogdata=[
                        'cp_id'=>$cp_id,
                        'mem_id'=>$info->mem_id,
                        'type'=>2,
                        'store_id'=>$info->store_id,
                        'change_val'=>$info->send_points,
                        'change_before'=>$meminfo->points_current,
                        'change_after'=>$meminfo->points_current+$info->send_points,
                        'sales_account_id'=>$info->shopping_account_id1,
                        'loginfo'=>json_encode(['title'=>'充值赠送']),
                        'create_account_id' => $info->create_account_id,
                        'update_account_id' => $info->update_account_id,
                        'create_account_real_name' => $info->create_account_real_name,
                        'update_account_real_name' => $info->update_account_real_name,
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark'=>$info->remark,
                    ];
                    MemberPointsChangelog::create($pointslogdata);

                    Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'points_current'=> DB::raw('points_current + ' . $info->send_points),
                        'points_total'=> DB::raw('points_total + ' . $info->send_points),
                        ]);

                }

                $info->mem_id>0 && Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                    'shopping_times'=>DB::raw('shopping_times + 1 '),
                    'shopping_money_total'=>DB::raw('shopping_money_total + '.$info->money),
                    'avg_shopping_money'=>intval(($meminfo->shopping_money_total+$info->money)/($meminfo->shopping_times+1)),
                    'max_shopping_money'=>($info->money>$meminfo->max_shopping_money?$info->money:$meminfo->max_shopping_money),
                    'min_shopping_money'=>($info->money<$meminfo->min_shopping_money?$info->money:$meminfo->min_shopping_money),
                    'last_shopping_at'=>$info->create_at
                ]);

                //计算绩效？
                //订单成功发送短信
                $info->change_before = $meminfo->pre_money;
                $info->change_after = $meminfo->pre_money + $info->money + $info->send_money;
                //收支流水
                Financial::createMoneyLog($cp_id,$info,$info->money,-1);
            }




            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '订单审核成功']);


    }

    /**
     * 审核取消
     */
    public function doorderauditcancel(Request $request){
        $id = $request->id ?? 0;
        $audit_remark=$request->audit_remark ?? '';
        if($audit_remark==''){
            return response()->json(['code' => '001', 'msg' => '请输入撤单原因']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info = OrderRecharge::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if (($accountinfo['type']==1 || $accountinfo['type']==2) && date('Y-m-d',$info->create_at)!=date('Y-m-d')) {

            return response()->json(['code' => '001', 'msg' => '店长只可撤单当日订单']);
        }

        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }
        // if($info->is_maker!=1){
        //     return response()->json(['code' => '001', 'msg' => '该订单挂单中不可审核']);
        // }
        OrderRecharge::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status'=>3,'audit_at'=>time(),'audit_remark'=>$audit_remark]);
        return response()->json(['code' => '000', 'msg' => '订单撤销成功']);

    }

    public function doorderauditcancelmore(Request $request){
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        $audit_remark=$request->audit_remark ?? '';
        if($audit_remark==''){
            return response()->json(['code' => '001', 'msg' => '请输入撤单原因']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info_more_arr = OrderRecharge::where(['cp_id' => $cp_id, 'audit_status'=>1])->whereIn('id', $ids)->get();

        if (count($info_more_arr) != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '存在已审核订单']);
        }


        if ($accountinfo['type']==1 || $accountinfo['type']==2) {
            $info_more_count = OrderRecharge::where(['cp_id' => $cp_id, 'audit_status'=>1])->where([['create_at','>=',strtotime(date('Y-m-d').'00:00:00')],['create_at','<=',time()]])
            ->whereIn('id', $ids)->count();
            if($info_more_count!=count($ids)){
                return response()->json(['code' => '001', 'msg' => '店长只可撤单当日订单']);
            }


        }

        OrderRecharge::where(['cp_id' => $cp_id, 'is_del' => 1, 'audit_status'=>1])->whereIn('id', $ids)->update(['audit_status' => 3, 'audit_at' => time(),'audit_remark'=>$audit_remark]);
        return response()->json(['code' => '000', 'msg' => '订单撤销成功']);
    }

    /**
     * 导出
     */
    public function doexport(Request $request){
        $list = OrderRecharge::getList($request)['list'];
        $exceldata = [];
        $row = [
            ['table_header'=>'充值开单'],
            [
                'store_name' => '所属门店',
                'mobile' => '会员电话',
                'real_name' => '会员姓名',
                'mem_card_no' => '会员卡号',
                'order_sn' => '订单号',
                'money'=>'充值金额',
                'send_money' => '赠送金额',
                'send_points'=>'赠送积分',
                'remark' => '备注',
                'sales_account_name' => '操作人',
                'order_at'=>'操作时间',
            ]
        ];
        foreach ($list as $val) {
            $exceldata[] = [
                'store_name' => $val['storeinfo']['store_name'],
                'mobile' => $val['memberinfo']['mobile']??'',
                'real_name' => $val['memberinfo']['real_name']??'',
                'mem_card_no' => $val['memberinfo']['mem_card_no']??'',
                'order_sn' => $val['order_sn'],
                'money'=>$val['money']/100,
                'send_money' => $val['send_money'],
                'send_points'=>$val['send_points'],
                'remark' => $val['remark'],
                'sales_account_name' => $val['shoppingaccountinfo1']['real_name'],
                'order_at'=>date('Y-m-d H:i:s',$val['order_at']),
            ];
        }
        $filename = '充值订单导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);



    }
    public function getorderprintdata(Request $request){
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        if($id<=0){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $data=ServicesOrderOrderRecharge::getOrderPrintData($id);
        return response()->json(['code' => '000', 'msg' => '获取成功','data'=>$data]);
    }

}
